package com.dyna.auth.listener;

import com.alibaba.fastjson.JSON;
import com.dyna.api.event.LoginUserEvent;
import com.dyna.constants.EsIndicesConstant;
import com.dyna.constants.RedisKeyConstant;
import com.dyna.constants.TokenConstant;
import com.dyna.domain.dto.LoginUser;
import com.dyna.enums.LoginStatusEnum;
import com.dyna.utils.EsUtil;
import com.dyna.utils.RdsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author zhoucaiwang
 * @date 2023/8/17
 */

@Slf4j
@Component
public class LoginUserEventListener {

    @Async
    @EventListener(classes = LoginUserEvent.class)
    public void saveLoginUserInfo(LoginUserEvent loginUserEvent) {
        // es登录日志存储
        EsUtil.initIndex(EsIndicesConstant.LOGIN_STATUS_INDEX);
        EsUtil.addData(EsIndicesConstant.LOGIN_STATUS_INDEX, loginUserEvent.getLoginInfo());
        if (LoginStatusEnum.LOGIN.getStatus().equals(loginUserEvent.getLoginInfo().getLoginStatus())) {
            // redis缓存用户信息
            LoginUser user = loginUserEvent.getUser();
            RdsUtil.set(RedisKeyConstant.USER_INFO_KEY + user.getUsername(), JSON.toJSONString(user), TokenConstant.TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
        }
    }

}
